/**
 * Copyright(c)2012 Beijing PeaceMap Co.,Ltd.
 * All right reserved. 
 */
package com.pmc.dwa.security.controller;

import java.sql.Timestamp;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.util.WebUtils;

import com.pmc.dwa.common.utils.Httptear;
import com.pmc.dwa.security.intercept.PmcSecurityMetadataSource;
import com.pmc.dwa.security.model.TRole;
import com.pmc.dwa.security.model.TUser;
import com.pmc.dwa.security.model.TUserDetails;
import com.pmc.dwa.security.service.IUserService;
import com.pmc.dwa.security.utils.EncryptUtils;
import com.pmc.dwa.security.utils.PmcAttributes;
import com.pmc.dwa.security.utils.SpringSecurityUtils;

/**
 * @description 首页请求地址
 * @author aokunsang
 * @date 2013-1-7
 */
@Controller
@RequestMapping("/rbac")
public class RbacController {

	@Autowired
	private IUserService userService;
	
	/* 获取菜单*/
	@RequestMapping(value="sysmenu",method={RequestMethod.GET})
	public void sysmenu(HttpServletRequest request,HttpServletResponse response){
		//先刷新权限列表
		PmcSecurityMetadataSource pmcMetadataSource = new PmcSecurityMetadataSource(userService);
		pmcMetadataSource.loadResourcesDefine();
		Object object = WebUtils.getSessionAttribute(request, PmcAttributes.PMC_USER_MENU);
		Httptear.ResponseResultByUTF8(object!=null ? object.toString() : "{}",response);
	}
	
	/*获取登录用户的基本信息*/
	@RequestMapping(value="getLoginUser",method={RequestMethod.GET})
	public @ResponseBody TUser getLoginUser(HttpSession session){
		String username = SpringSecurityUtils.getCurrentUser()==null ? "" :SpringSecurityUtils.getCurrentUser().getUsername();
		TUser user = userService.findUserByName(username);
		if(user==null) return new TUser();
		//把Base64加密后密码放入user
		user.setPassword_base64(session.getAttribute(PmcAttributes.PMC_LAST_PASSWORD_KEY)!=null ? (String)session.getAttribute(PmcAttributes.PMC_LAST_PASSWORD_KEY) : "");
		List<TRole> userRoles = userService.findUserRolesByUsername(username);
		user.setUserRoles(userRoles);
		return user;
	}
	
	/* 更新用户信息*/
	@RequestMapping(value="uptLoginUser",method={RequestMethod.POST})
	public void uptLoginUser(HttpServletResponse response,TUser user){
		
		TUserDetails userDetail = SpringSecurityUtils.getCurrentUser();
		if(userDetail == null){
			Httptear.ResponseResultByUTF8ForEscape("{success:'false',msg:'抱歉，登录已超时！请您重新登录。'}", response);
			return;
		}
		String userid = userDetail.getUserid();
		user.setId(userid);
		user.setReg_time(new Timestamp(System.currentTimeMillis()));
		try {
			userService.editUserPartinfo(user);
			Httptear.ResponseResultByUTF8ForEscape("{success:'true',action:'uptinfo',msg:''}", response);
		} catch (Exception ex) {
			Httptear.ResponseResultByUTF8ForEscape("{success:'false',msg:'"+ex.getMessage()+"'}", response);
		}
	}
	/* 修改密码*/
	@RequestMapping(value="uptPwd",method={RequestMethod.POST})
	public void uptPwd(HttpServletResponse response,HttpServletRequest request,
			 String cur_password,String new_password,String confirm_password){
		TUserDetails userDetail = SpringSecurityUtils.getCurrentUser();
		if(userDetail == null){
			Httptear.ResponseResultByUTF8ForEscape("{success:'false',msg:'抱歉，登录已超时！请您重新登录。'}", response);return;
		}
		String uid = userDetail.getUserid();    //用户id
		String username = userDetail.getUsername();
		String password = userDetail.getPassword();  //用户密码
		
		if(StringUtils.isEmpty(cur_password) || StringUtils.isEmpty(new_password) || StringUtils.isEmpty(confirm_password)){
			Httptear.ResponseResultByUTF8ForEscape("{success:'false',msg:'提交数据不完整，无法继续。'}", response);
		}else if(!new_password.equals(confirm_password)){
			Httptear.ResponseResultByUTF8ForEscape("{success:'false',msg:'新密码和确认密码不是同一个，请检查。'}", response);
		}else if(!password.equals(EncryptUtils.md5(cur_password))){
			Httptear.ResponseResultByUTF8ForEscape("{success:'false',msg:'抱歉，您输入的当前登录密码不正确，请重试。'}", response);
		}else{
			try {
				userService.editLoginUserPwd(uid, EncryptUtils.md5(new_password));
				//设置权限验证中的密码
				SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(username,new_password));
				Httptear.ResponseResultByUTF8ForEscape("{success:'true',action:'uptpwd',msg:''}", response);
			} catch (Exception ex) {
				Httptear.ResponseResultByUTF8ForEscape("{success:'false',msg:'"+ex.getMessage()+"'}", response);
			}
		}
	}
}
